<template>
  <div class="min-h-screen bg-gray-50">
    <div class="main-container">
      <h2 class="page-title">个人事务统计</h2>

      <!-- 统计图表区域 -->
      <div class="statistics-summary">
        <h3 class="summary-title">年度事务统计概览</h3>
        <div class="charts-section">
          <!-- 折线图容器 -->
          <div class="chart-container">
            <h4 class="chart-title">年度事务处理趋势</h4>
            <!-- 添加v-if="!loading"确保有数据再渲染图表 -->
            <v-chart v-if="!loading" class="chart" :option="lineChartOptions" autoresize />
          </div>
          <!-- 饼图容器 -->
          <div class="chart-container">
            <h4 class="chart-title">年度事务类型分布</h4>
            <v-chart v-if="!loading" class="chart" :option="pieChartOptions" autoresize />
          </div>
        </div>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-section">
        <div class="filter-grid">
          <!-- 事务名称搜索框 -->
          <div class="search-container">
            <input
              type="text"
              placeholder="输入事务名称进行搜索"
              class="search-input"
              v-model="filters.name"
            />
          </div>

          <!-- 统计日期选择 -->
           <div class="date-filter-item">
            <input
                type="date"
                placeholder="选择统计日期"
                class="date-input"
                v-model="filters.statisticDate"
            />
             <button
                v-if="filters.statisticDate"
                @click="filters.statisticDate = ''"
                class="clear-btn"
              >
                清除
              </button>
           </div>
        </div>
      </div>

      <!-- 事务列表 -->
      <div class="table-container">
        <div class="table-wrapper">
          <table class="log-table">
            <thead class="table-header">
              <tr>
                <th class="table-th">序号</th>
                <th class="table-th">事务名称</th>
                <th class="table-th">类型/分组</th>
                <th class="table-th">统计前状态</th>
                <th class="table-th">统计时间</th>
                <th class="table-th">接收者</th>
                <th class="table-th">操作</th>
              </tr>
            </thead>
            <tbody class="table-body">
              <!-- 添加加载状态提示 -->
              <tr v-if="loading">
                <td colspan="7" class="text-center-custom">正在加载数据...</td>
              </tr>
              <!-- 无数据时的提示 -->
              <tr v-else-if="filteredAffairs.length === 0">
                <td colspan="7" class="text-center-custom">暂无个人统计数据</td>
              </tr>
              <!-- 渲染数据列表 -->
              <tr v-else v-for="(affair, index) in paginatedAffairs" :key="affair.id" class="table-row">
                <td class="table-td">{{ indexOfFirstLog + index + 1 }}</td>
                <td class="table-td user-name" :title="affair.name">
                  {{ truncateText(affair.name, 20) }}
                </td>
                <td class="table-td">{{ affair.group }}</td>
                <td class="table-td">
                  <span :class="['status-badge', statusClasses[affair.originalStatus] || 'status-default']">
                    {{ affair.originalStatus }}
                  </span>
                </td>
                <td class="table-td">{{ affair.statisticAt }}</td>
                <td class="table-td">{{ affair.publisher }}</td>
                <td class="table-td action-buttons">
                    <button class="detail-btn" @click="showDetails(affair)">
                      详情
                    </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="totalPages > 1">
           <div class="pagination-desktop">
            <div class="pagination-info">
              <p class="pagination-text">
                显示第 <span class="font-medium">{{ indexOfFirstLog + 1 }}</span> 到
                <span class="font-medium">{{ Math.min(indexOfLastLog, filteredAffairs.length) }}</span> 条，
                共 <span class="font-medium">{{ filteredAffairs.length }}</span> 条记录
              </p>
            </div>
            <div class="pagination-controls">
              <button @click="prevPage" :disabled="currentPage === 1" class="page-btn">
                上一页
              </button>
              <template v-for="page in visiblePages" :key="page">
                <button v-if="typeof page === 'number'" @click="goToPage(page)" :class="['page-btn', { active: page === currentPage }]">
                  {{ page }}
                </button>
                <span v-else class="page-ellipsis">...</span>
              </template>
              <button @click="nextPage" :disabled="currentPage === totalPages" class="page-btn">
                下一页
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <div v-if="selectedAffair" class="modal-overlay" @click.self="closeModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">事务详情</h3>
          <button @click="closeModal" class="modal-close-btn">×</button>
        </div>
        <div class="modal-body">
          <div class="detail-item">
            <span class="detail-label">完整名称:</span>
            <p class="detail-value">{{ selectedAffair.name }}</p>
          </div>
          <div class="detail-item">
            <span class="detail-label">接收者:</span>
            <span class="detail-value">{{ selectedAffair.publisher }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">类型/分组:</span>
            <span class="detail-value">{{ selectedAffair.group }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">开始时间:</span>
            <span class="detail-value">{{ selectedAffair.startTime || '未指定' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">结束时间:</span>
            <span class="detail-value">{{ selectedAffair.endTime || '未指定' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">统计时间:</span>
            <span class="detail-value">{{ selectedAffair.statisticAt || '未归档' }}</span>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="closeModal" class="close-action-btn">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart, LineChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components';
import VChart from 'vue-echarts';
// 【确认导入路径】确保这里的路径是正确的
import { getPersonalArchiveList } from '@/api/Archive';

// ECharts 组件注册
use([
  CanvasRenderer,
  PieChart,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
]);

// --- 响应式状态定义 (保持不变) ---
const allAffairs = ref([]);
const loading = ref(true);
const filters = ref({ name: '', statisticDate: '' });
const currentPage = ref(1);
const logsPerPage = ref(10);
const selectedAffair = ref(null);
const statusClasses = ref({
  '已完成': 'status-completed',
  '已取消': 'status-cancelled',
});
// 【新增】用于存储从localStorage获取的用户ID
const currentUserId = ref(null);


// --- 生命周期函数 ---
onMounted(() => {
  // 【核心改动 1】: 将数据获取逻辑封装在 onMounted 钩子函数中
  // 1. 从 localStorage 获取用户信息
  const userInfoString = localStorage.getItem('userInfo');

  if (userInfoString) {
    const userInfo = JSON.parse(userInfoString);
    currentUserId.value = userInfo.userId;

    // 2. 确认获取到 userId后，再调用 fetchData，并把ID传进去
    if (currentUserId.value) {
      console.log('组件已挂载，开始为用户获取数据，ID:', currentUserId.value);
      fetchData(currentUserId.value);
    } else {
      console.error('用户信息中未找到 userId。');
      loading.value = false; // 停止加载状态
      // 这里可以添加提示，告知用户数据加载失败
    }
  } else {
    console.error("未在 localStorage 中找到用户信息，用户可能未登录。");
    loading.value = false; // 停止加载状态
    // 这里可以重定向到登录页
    // import { useRouter } from 'vue-router';
    // const router = useRouter();
    // router.push('/login');
  }
});


// --- API 数据获取与处理 ---
// 【核心改动 2】: 修改 fetchData 函数，使其接收 userId 参数
async function fetchData(userId) {
  loading.value = true;
  try {
    // 【核心改动 3】: 调用API时传入 userId
    const data = await getPersonalArchiveList(userId);

    // 将后端数据映射为前端需要的格式 (保持不变)
    allAffairs.value = data.map(item => ({
      id: item.archiveId,
      name: item.transactionName,
      group: item.groupName,
      originalStatus: item.status,
      startTime: item.startTime,
      endTime: item.endTime,
      publisher: item.publisherName,
      statisticAt: item.completionDate,
    }));
    console.log('成功获取并处理了个人档案数据:', allAffairs.value);
  } catch (error) {
    console.error('获取个人归档列表失败:', error);
    // 清空数据，避免显示旧数据
    allAffairs.value = [];
  } finally {
    loading.value = false;
  }
}

// --- 计算属性 (以下所有计算属性都无需修改) ---

// 文本截断辅助函数
function truncateText(text, maxLength) {
  if (!text || text.length <= maxLength) {
    return text;
  }
  return text.slice(0, maxLength) + '...';
}

// 饼图配置
const pieChartOptions = computed(() => {
  // ... (代码保持不变)
  const groupCounts = allAffairs.value.reduce((acc, affair) => {
    acc[affair.group] = (acc[affair.group] || 0) + 1;
    return acc;
  }, {});
  const dataForPie = Object.keys(groupCounts).map(key => ({
    name: key,
    value: groupCounts[key],
  }));
  return {
    tooltip: { trigger: 'item', formatter: '{b} : {c} ({d}%)' },
    legend: { orient: 'vertical', left: 'left', top: 'center' },
    series: [
      {
        name: '事务类型', type: 'pie', radius: ['40%', '70%'],
        center: ['65%', '50%'], avoidLabelOverlap: false,
        itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
        label: { show: false }, emphasis: { label: { show: true, fontSize: '20', fontWeight: 'bold' } },
        labelLine: { show: false }, data: dataForPie,
      },
    ],
  };
});

// 折线图配置
const lineChartOptions = computed(() => {
  // ... (代码保持不变)
  const monthlyCounts = Array(12).fill(0);
  allAffairs.value.forEach(affair => {
    if (affair.statisticAt) {
      const month = new Date(affair.statisticAt).getMonth();
      if (month >= 0 && month < 12) {
        monthlyCounts[month]++;
      }
    }
  });
  return {
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'] },
    yAxis: { type: 'value' },
    series: [
      {
        name: '处理量', data: monthlyCounts, type: 'line', smooth: true, itemStyle: { color: '#3b82f6' },
        areaStyle: { color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, colorStops: [{ offset: 0, color: 'rgba(59, 130, 246, 0.4)' }, { offset: 1, color: 'rgba(59, 130, 246, 0)' }] } }
      },
    ],
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }
  };
});

// 筛选后的数据
const filteredAffairs = computed(() => {
  // ... (代码保持不变)
  if (!allAffairs.value) return [];
  return allAffairs.value.filter(affair => {
    const nameMatch = affair.name ? affair.name.toLowerCase().includes(filters.value.name.toLowerCase()) : true;
    const dateMatch = !filters.value.statisticDate || (affair.statisticAt && affair.statisticAt.startsWith(filters.value.statisticDate));
    return nameMatch && dateMatch;
  });
});

// --- 分页相关计算属性 (代码保持不变) ---
const totalPages = computed(() => Math.ceil(filteredAffairs.value.length / logsPerPage.value));
const indexOfLastLog = computed(() => currentPage.value * logsPerPage.value);
const indexOfFirstLog = computed(() => indexOfLastLog.value - logsPerPage.value);
const paginatedAffairs = computed(() => {
  if (filteredAffairs.value.length > 0 && indexOfFirstLog.value >= filteredAffairs.value.length) {
    currentPage.value = 1;
  }
  return filteredAffairs.value.slice(indexOfFirstLog.value, indexOfLastLog.value);
});

const visiblePages = computed(() => {
  const total = totalPages.value;
  const current = currentPage.value;
  if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);
  const pages = [1];
  if (current > 4) pages.push('...');
  const start = Math.max(2, current - 2);
  const end = Math.min(total - 1, current + 2);
  for (let i = start; i <= end; i++) pages.push(i);
  if (current < total - 3) pages.push('...');
  pages.push(total);
  return pages;
});

// --- 方法 (代码保持不变) ---
function showDetails(affair) { selectedAffair.value = affair; }
function closeModal() { selectedAffair.value = null; }

function goToPage(page) {
  if (page >= 1 && page <= totalPages.value) currentPage.value = page;
}
function prevPage() {
  if (currentPage.value > 1) currentPage.value--;
}
function nextPage() {
  if (currentPage.value < totalPages.value) currentPage.value++;
}
</script>

<style scoped>
/* 基础与布局 */
.min-h-screen { min-height: 100vh; }
.bg-gray-50 { background-color: #f9fafb; }
.main-container { max-width: 1200px; margin: 0 auto; padding: 1.5rem; }
.page-title { font-size: 1.875rem; font-weight: 700; color: #111827; margin-bottom: 1.5rem; }

/* 统计概览区域 */
.statistics-summary { background-color: white; border-radius: 8px; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1); padding: 1.5rem; margin-bottom: 1.5rem; }
.summary-title { font-size: 1.25rem; font-weight: 600; color: #111827; margin-bottom: 1.5rem; padding-bottom: 1rem; border-bottom: 1px solid #e5e7eb; }
.charts-section { display: flex; gap: 1.5rem; flex-wrap: wrap; }
.chart-container { flex: 1; min-width: 300px; padding: 1rem; border: 1px solid #f3f4f6; border-radius: 8px; }
.chart-title { font-size: 1rem; font-weight: 600; color: #374151; margin-bottom: 1rem; text-align: center; }
.chart { height: 300px; width: 100%; }

/* 筛选区域 */
.filter-section { background-color: white; border-radius: 8px; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1); padding: 1.5rem; margin-bottom: 1.5rem; position: sticky; top: 0; z-index: 10; }
.filter-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1.5rem; }
.search-input, .date-input { width: 100%; padding: 0.5rem 0.75rem; border: 1px solid #d1d5db; border-radius: 6px; font-size: 0.875rem; }
.date-filter-item { display: flex; align-items: center; gap: 0.5rem; }
.clear-btn { padding: 0.5rem 0.75rem; background-color: #f3f4f6; color: #6b7280; border: 1px solid #d1d5db; border-radius: 6px; font-size: 0.75rem; cursor: pointer; }

/* 表格样式 */
.table-container { background-color: white; border-radius: 8px; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1); overflow: hidden; margin-top: 1.5rem; }
.table-wrapper { overflow-x: auto; }
.log-table { width: 100%; border-collapse: collapse; }
.table-header { background-color: #f9fafb; }
.table-th { padding: 0.75rem 1.5rem; text-align: left; font-weight: 600; color: #374151; font-size: 0.875rem; border-bottom: 1px solid #e5e7eb; }
.table-td { padding: 1rem 1.5rem; font-size: 0.875rem; color: #6b7280; vertical-align: middle; border-bottom: 1px solid #f3f4f6;}
.user-name { font-weight: 600; color: #111827; }
.detail-btn { padding: 0.25rem 0.75rem; background-color: #f3f4f6; color: #374151; border: 1px solid #d1d5db; border-radius: 4px; font-size: 0.75rem; cursor: pointer; }
.text-center-custom { padding: 2rem; text-align: center; color: #6b7280; }

/* 状态徽章 */
.status-badge { display: inline-block; padding: 0.25rem 0.75rem; border-radius: 12px; font-size: 0.75rem; font-weight: 500; }
.status-badge.status-completed { background-color: #dcfdf7; color: #065f46; }
.status-badge.status-cancelled { background-color: #fee2e2; color: #991b1b; }
.status-badge.status-processing { background-color: #fef9c3; color: #854d0e; }
.status-badge.status-todo { background-color: #dbeafe; color: #1e40af; }
.status-badge.status-read { background-color: #eef2ff; color: #3730a3; }
.status-badge.status-default { background-color: #f3f4f6; color: #374151; }

/* 分页 */
.pagination-container { padding: 1rem 1.5rem; border-top: 1px solid #e5e7eb; }
.pagination-desktop { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem;}
.pagination-info { font-size: 0.875rem; color: #6b7280; margin: 0; }
.font-medium { font-weight: 500; }
.pagination-controls { display: flex; align-items: center; gap: 0.5rem; }
.page-btn {
  padding: 0.4rem 0.8rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background-color: white;
  color: #374151;
  font-size: 0.875rem;
  cursor: pointer;
  transition: background-color 0.2s, color 0.2s;
}
.page-btn:hover:not(:disabled) {
  background-color: #f3f4f6;
}
.page-btn.active {
  background-color: #3b82f6;
  color: white;
  border-color: #3b82f6;
}
.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.page-ellipsis {
  padding: 0.4rem 0.2rem;
  color: #6b7280;
}

/* 模态框 */
/* ... (模态框样式保持不变) ... */
.modal-overlay { position: fixed; inset: 0; background-color: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 50; padding: 1rem; }
.modal-container { background-color: white; border-radius: 8px; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1); max-width: 600px; width: 100%; max-height: 90vh; overflow-y: auto; }
.modal-content { padding: 1.5rem 2rem; }
.modal-title { font-size: 1.25rem; font-weight: 600; color: #111827; margin: 0 0 1.5rem 0; }
.modal-body { display: flex; flex-direction: column; gap: 1rem; }
.detail-item { display: flex; flex-direction: column; gap: 0.25rem; }
.detail-label { font-size: 0.8rem; font-weight: 600; color: #374151; margin: 0; }
.detail-value { font-size: 0.875rem; color: #6b7280; margin: 0; padding: 0.5rem 0.75rem; background-color: #f9fafb; border-radius: 4px; border: 1px solid #e5e7eb; word-break: break-all; }
.modal-footer { margin-top: 2rem; display: flex; justify-content: flex-end; }
.modal-close-btn { padding: 0.6rem 1.2rem; background-color: #6b7280; color: white; border: none; border-radius: 6px; font-size: 0.875rem; cursor: pointer; transition: background-color 0.2s; }
.modal-close-btn:hover { background-color: #4b5563; }

/* 响应式 */
@media (max-width: 768px) {
  .pagination-desktop {
    flex-direction: column;
    align-items: center;
  }
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 2rem;
  border-radius: 0.5rem;
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 1rem;
  margin-bottom: 1rem;
}

.modal-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #111827;
}

.modal-close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #9ca3af;
}
.modal-close-btn:hover {
  color: #111827;
}

.modal-body {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.detail-item {
  display: flex;
  flex-direction: column;
}

.detail-label {
  font-size: 0.875rem;
  color: #6b7280;
  font-weight: 500;
  margin-bottom: 0.25rem;
}

.detail-value {
  font-size: 1rem;
  color: #1f2937;
  word-wrap: break-word; /* 确保长文本能换行 */
}

.modal-footer {
  margin-top: 1.5rem;
  padding-top: 1rem;
  border-top: 1px solid #e5e7eb;
  text-align: right;
}

.close-action-btn {
  background-color: #4f46e5;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  border: none;
  cursor: pointer;
  transition: background-color 0.2s;
}
.close-action-btn:hover {
  background-color: #4338ca;
}
</style>
